package com.ljkj.cordial.chat.activity;

import android.app.Activity;
import android.bluetooth.BluetoothHeadset;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.ArrayMap;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lanjiu.lib.imclient.bus.EventConstants;
import com.lanjiu.lib.imclient.bus.MessageEvent;
import com.lanjiu.lib.imclient.dto.FriendDto;
import com.lanjiu.lib.imclient.dto.GroupDto;
import com.lanjiu.lib.imclient.dto.GroupMemberDto;
import com.lanjiu.lib.imclient.dto.extra.UserChatTable;
import com.lanjiu.lib.imclient.ims.IMSClientHelper;
import com.lanjiu.lib.imclient.ims.IMSContacts;
import com.lanjiu.lib.imclient.user.UserPreferences;
import com.lanjiu.lib.utils.CollectionUtils;
import com.lanjiu.lib.utils.GUID;
import com.lanjiu.lib.utils.json.JsonUtils;
import com.lanjiu.lib.utils.sp.SPKeys;
import com.lanjiu.lib.utils.sp.SharedPreferenceHelper;
import com.lanjiu.lib.utils.th.Threader;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.adapter.ChatAdapter;
import com.ljkj.cordial.chat.adapter.ChatSendBoxAdapter;
import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.bean.ChatTableUnit;
import com.ljkj.cordial.chat.bean.EmptyMessageEvent;
import com.ljkj.cordial.chat.bean.FontSize;
import com.ljkj.cordial.chat.bean.MsgType;
import com.ljkj.cordial.chat.dao.AlbumTableBean;
import com.ljkj.cordial.chat.dao.ChatTableBean;
import com.ljkj.cordial.chat.dao.UserTableBean;
import com.ljkj.cordial.chat.dao.notify.ChatContentTable;
import com.ljkj.cordial.chat.dao.notify.FriendTable;
import com.ljkj.cordial.chat.dao.notify.GroupMemberTable;
import com.ljkj.cordial.chat.dao.notify.GroupTable;
import com.ljkj.cordial.chat.notify.NotificationUtils;
import com.ljkj.cordial.chat.plugins.receiver.HeadsetPlugReceiver;
import com.ljkj.cordial.chat.plugins.receiver.ScreenPlugReceiver;
import com.ljkj.cordial.chat.presenter.AChatPresenter;
import com.ljkj.cordial.chat.presenter.OnChatViewItemClickListener;
import com.ljkj.cordial.chat.ui.AppEventActivity;
import com.ljkj.cordial.chat.ui.ChatUtils;
import com.ljkj.cordial.chat.ui.views.GroupChatView;
import com.ljkj.cordial.chat.util.AlbumManageUtil;
import com.ljkj.cordial.chat.util.AtUtil;
import com.ljkj.cordial.chat.util.EPSoftKeyBoardListener;
import com.ljkj.cordial.chat.util.ObserverThread;
import com.ljkj.cordial.chat.util.ReadFinishCycTimeUtil;
import com.ljkj.cordial.chat.util.ReadFinishTask;
import com.ljkj.cordial.chat.util.SpeechVoiceUtil;
import com.ljkj.cordial.chat.util.WxVideoPlayUtil;
import com.ljkj.cordial.chat.widget.ChatItemPop;
import com.ljkj.cordial.chat.widget.RectButtonHintDialog;
import com.ljkj.cordial.lengthtcpheartbeat.NetworkUtil;
import com.nic.view.util.AndroidFileUtil;
import com.nic.view.util.DateTimeUtil;
import com.nic.view.util.FileSizeUtil;
import com.nic.view.util.JLog;
import com.nic.view.util.JToast;
import com.nic.view.util.SharedUtils;
import com.nic.view.util.Utility;
import com.nic.view.widget.RecycleViewDivide;
import com.nic.view.widget.WrapContentLinearLayoutManager;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.util.AlbumUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.github.rockerhieu.emojicon.EmojiconEditText;
import io.github.rockerhieu.emojicon.EmojiconPage;
import io.github.rockerhieu.emojicon.EmojiconsFragment;
import io.github.rockerhieu.emojicon.EmojiconsView;
import io.github.rockerhieu.emojicon.emoji.Emojicon;

/**
 * 群聊
 */
public class GroupChatActivity extends AppEventActivity<GroupChatView> implements OnChatViewItemClickListener, ChatAdapter.OnRefreshBottomListener, AdapterView.OnItemClickListener {
//    private static int REQ_CODE_ANNEX = 222;


    ImageView ivEar;
    @BindView(R.id.iv_take_voice)
    ImageView ivTakeVoice;
    @BindView(R.id.et_text)
    EmojiconEditText etText;
    @BindView(R.id.tv_speech)
    TextView tvSpeech;
    @BindView(R.id.iv_emoj)
    ImageView ivEmoj;
    @BindView(R.id.iv_more)
    ImageView ivMore;
    @BindView(R.id.tv_send)
    TextView tvSend;
    @BindView(R.id.emojicons_view)
    EmojiconsView emojiconsView;
    @BindView(R.id.gv_box)
    GridView gvBox;
    @BindView(R.id.gv_panel)
    FrameLayout gvPanel;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.cb_all)
    CheckBox cbAll;
    @BindView(R.id.tv_delete_all)
    TextView tvDeleteAll;
    @BindView(R.id.ll_select_item)
    LinearLayout llSelectItem;
    @BindView(R.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R.id.progress)
    ProgressBar progress;
    @BindView(R.id.v_tran)
    View vTran;
    @BindView(R.id.tv_unread)
    TextView tvUnread;
    @BindView(R.id.tv_atel)
    TextView tvAtel;

    private WrapContentLinearLayoutManager mLinearLayoutManager;
    private ChatAdapter chatAdater;
    private int chatType;
    private ChatItemPop chatItemPop;
    private ChatTableBean longItem;
    private int readFinishTime;
    private boolean isReadFinish;
    private String targetId;
    private String targetName;
    private String targetType;
    private ChatSendBoxAdapter chatSendBoxAdapter;
    private String mFriendAlias;
    private int offset = 0;
    private int limit = 30;
    private boolean isLoadfinish;
    private volatile int unreadTime = 0;
    private LinkedHashMap<Long, String> atelMap = new LinkedHashMap<>();
    private boolean initUnread;
    private boolean hasMsg;//是否有消息
    private long lastItemTime = 0L;
    private int lastChatType = 0;
    private long historyTimeUnit = 60 * 1000;//历史时间超时间隔
    private UserTableBean sendUser;
    private boolean isPause;

    public String getTargetId() {
        return targetId;
    }

    public String getTargetType() {
        return targetType;
    }

    public int getChatType() {
        return chatType;
    }

    private ScreenPlugReceiver mScreenPlugReceiver;

    @Override
    public int getContentLayoutId() {
        return R.layout.activity_group_chat;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        chatType = getIntent().getIntExtra(Canstants.KEY_TYPE, Canstants.GROUP_CHAT);
        targetName = getIntent().getStringExtra(Canstants.KEY_CHAT_TARGET_NAME);
        targetId = getIntent().getStringExtra(Canstants.KEY_CHAT_TARGET_ID);
        targetType = getIntent().getStringExtra(Canstants.KEY_CHAT_TARGET_TYPE);
        hasMsg = getIntent().getBooleanExtra(Canstants.KEY_CLEAR_TASK, hasMsg);
        sendUser = UserTableBean.getCurrentUser();
        recycleView.post(() -> {
            NotificationUtils.setupTargetId(targetId);
            NotificationUtils.clearNotify(this, targetId, chatType);    // 清除通知
            initFriendNickName();
            initContentView();
        });
        mScreenPlugReceiver = new ScreenPlugReceiver();
        mScreenPlugReceiver.register(this, isOpen -> {
            if (isOpen) NotificationUtils.setupTargetId(targetId);
            else NotificationUtils.removeTargetId();
        });
    }

    private void initContentView() {
        setAllowContinueClick(true);
        emojiconsView.setPages(Arrays.asList(
                new EmojiconPage(Emojicon.TYPE_PEOPLE, null, false, R.drawable.ic_emoji_people_light)));
        emojiconsView.setOnEmojiconViewBackListener(new EmojiconsView.OnEmojiconViewBackListener() {
            @Override
            public void onBackView(View view) {
                EmojiconsFragment.backspace(etText);
            }
        });
        emojiconsView.setOnEmojiconClickedListener(new EmojiconsView.OnEmojiconClickedListener() {
            @Override
            public void onEmojiconClicked(Emojicon emojicon) {
                EmojiconsFragment.input(etText, emojicon);
            }
        });
//        swipe.setColorSchemeResources(R.color.gray_300);
//        swipe.setProgressBackgroundColorSchemeResource(android.R.color.white);
//        swipe.setProgressViewEndTarget(true, 128);
//        swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                if (!isLoadfinish) {
//                    swipe.setRefreshing(true);
//                    getChatList(chatType, targetId, targetId, false);
//                } else {
//                    refreshFinish();
//                }
//            }
//        });
        mLinearLayoutManager = new WrapContentLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mLinearLayoutManager.setStackFromEnd(true);
        recycleView.setHasFixedSize(true);
        recycleView.setNestedScrollingEnabled(false);
//        recycleView.setItemViewCacheSize(10);
//        recycleView.setDrawingCacheEnabled(true);
//        recycleView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_AUTO);
        recycleView.setFocusable(false);
        recycleView.setFocusableInTouchMode(false);
        recycleView.setLayoutManager(mLinearLayoutManager);
        recycleView.setItemAnimator(null);
        recycleView.addItemDecoration(new RecycleViewDivide(this, LinearLayoutManager.VERTICAL, getResources().getDimensionPixelOffset(R.dimen.dimen_list_padding)));
        chatAdater = new ChatAdapter(this, chatType, recycleView);
        chatAdater.setOnChatViewResultListener(this);
        chatAdater.setRefreshBottomListener(this);
        recycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
//                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
//                    chatAdater.setLoadAccess(true);
//                    if (progress.getVisibility() == View.GONE) {
//                        refreshVisibleItems();
//                    }
//                } else {
//                    chatAdater.setLoadAccess(false);
//                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                if (!recyclerView.canScrollVertically(-1)) {
                    //top
//                    limit = mLinearLayoutManager.getChildCount();
                    if (offset != 0) {
                        if (!isLoadfinish) {
                            progress.setVisibility(View.VISIBLE);
                            recyclerView.post(() -> getChatList(chatType, targetId, targetId, false));
                        } else {
                            refreshFinish();
                        }
                    }
                } else if (!recyclerView.canScrollVertically(1)) {
                    //bottom
                    if (initUnread && mLinearLayoutManager.findLastVisibleItemPosition() == chatAdater.getItemCount() - 1) {
                        tvUnread.setVisibility(View.GONE);
                        unreadTime = 0;
                    }
                } else if (dy < 0) {
                    //up
                    if (offset == 1) {
                        unreadTime = 0;
                        tvUnread.setVisibility(View.GONE);
                        UnReadDown();
                    }
                } else if (dy > 0) {
                    //bottom
                }
            }
        });
        recycleView.setAdapter(chatAdater);
//        EmojiAdapter emojiAdapter = new EmojiAdapter(this);
//        gv.setAdapter(emojiAdapter);
//        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                String tag = (String) parent.getItemAtPosition(position);
//                EmojiPackage.insertEmoj(mContext, etText, tag);
//            }
//        });
        chatSendBoxAdapter = new ChatSendBoxAdapter();
        gvBox.setAdapter(chatSendBoxAdapter);
        gvBox.setOnItemClickListener(this);
        SpeechVoiceUtil.getInstance().init(this, tvSpeech, new SpeechVoiceUtil.OnSpeechResultCallback() {
            @Override
            public void onStart() {
                AlbumManageUtil.getInstance().stopVoice();
            }

            @Override
            public void onResult(AlbumFile albumFile) {
                sendChat(MsgType.Voice, null, albumFile);
            }
        });
        EPSoftKeyBoardListener.setListener(this, new EPSoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                switchEmo(true);
                switchGvBox(true);
                MoveToEnd();
            }

            @Override
            public void keyBoardHide(int height) {
//                refreshVisibleItems();
            }
        });
        chatItemPop = new ChatItemPop(this);
        chatItemPop.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (ChatItemPop.DEL.equals(chatItemPop.getPositionItem(position)) || ChatItemPop.REDEL.equals(chatItemPop.getPositionItem(position))) {//删除

                    if (tvUnread.getVisibility() == View.VISIBLE) {
                        --unreadTime;
                        if (unreadTime == 0) {
                            tvUnread.setVisibility(View.GONE);
                        } else {
                            tvUnread.setText(String.format("%d条未读消息", unreadTime));
                        }
                    }
                    if (recycleView.isComputingLayout()) {
                        recycleView.postDelayed(() -> chatAdater.remove(chatItemPop.getPosition()), 300);
                    } else {
                        chatAdater.remove(chatItemPop.getPosition());
                    }
                    chatItemPop.getPopupWindow().dismiss();
                    if (longItem != null) {
                        deleteChats(Collections.singletonList(longItem));
                        ChatTableBean.delete(longItem);
                    }
                    signLast();
                } else if (ChatItemPop.MUL_CHOOSE.equals(chatItemPop.getPositionItem(position))) {//多选
                    chatItemPop.getPopupWindow().dismiss();
                    chatAdater.selectVisible();
                    llSelectItem.setVisibility(View.VISIBLE);
                    setSelectAllVisibility(View.VISIBLE);
                    etText.setEnabled(false);
                    ivTakeVoice.setEnabled(false);
                    gvBox.setVisibility(View.GONE);
                } else if (ChatItemPop.NO_AUDIO_PLAY.equals(chatItemPop.getPositionItem(position))) {//静音播放
                    if (longItem != null) {
                        if (!TextUtils.isEmpty(longItem.getAlbumId()) && Long.parseLong(longItem.getAlbumId()) > 0) {
                            AlbumTableBean al = AlbumTableBean.queryById(Long.parseLong(longItem.getAlbumId()));
                            if (!TextUtils.isEmpty(al.getMPath())) {
                                Intent intent = AndroidFileUtil.getMp4FileIntent(al.getMPath(), true);
                                if (intent != null) {
                                    startActivity(intent);
                                }
                                SpeechVoiceUtil.setAudioMute(mContext, true);
                            }
                        }
                    }
                }
//                else if (position == 2) {//转发好友
//                    chatItemPop.getPopupWindow().dismiss();
//                    TransmitFriendActivity.jumpTo((Activity) mContext, new EmptyMessageEvent(Canstants.SINGLE_CHAT, targetId, targetName, targetType, String.valueOf(longItem.getId())));
//                } else if (position == 3) {//转发群组
//                    chatItemPop.getPopupWindow().dismiss();
//                    TransmitGroupActivity.jumpTo((Activity) mContext, new EmptyMessageEvent(Canstants.GROUP_CHAT, targetId, targetName, targetType, String.valueOf(longItem.getId())));
//                }
            }
        });
        chatItemPop.setOnPlayModeChangeListener(this::setupTitle);
        chatItemPop.getPopupWindow().setOnDismissListener(() -> vTran.setVisibility(View.GONE));
        cbAll.setChecked(false);
        cbAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    chatAdater.selectAll();
                    tvDeleteAll.setText(String.format("(%s)", chatAdater.selected().size()));
                } else {
                    chatAdater.unselectAll();
                    tvDeleteAll.setText("(0)");
                }
            }
        });
        tvDeleteAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<ChatTableBean> selected = chatAdater.selected();
                deleteChats(selected);
                ChatTableBean.delete(selected);
                chatAdater.removeSelected();
                chatAdater.selectInVisible();
                llSelectItem.setVisibility(View.GONE);
                setSelectAllVisibility(View.GONE);
                etText.setEnabled(true);
                ivTakeVoice.setEnabled(true);
                if (tvUnread.getVisibility() == View.VISIBLE) {
                    unreadTime = 0;
                    tvUnread.setVisibility(View.GONE);
                }
                signLast();
            }
        });
        setOnBackListener(0, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cbAll.getVisibility() == View.VISIBLE ||
                        tvDeleteAll.getVisibility() == View.VISIBLE) {
                    llSelectItem.setVisibility(View.GONE);
                    setSelectAllVisibility(View.GONE);
                    etText.setEnabled(true);
                    ivTakeVoice.setEnabled(true);
                    cbAll.setChecked(false);
                    chatAdater.selectInVisible();
                } else {
                    finish();
                }
            }
        });
        etText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s.toString())) {
                    tvSend.setVisibility(View.VISIBLE);
                    ivMore.setVisibility(View.GONE);
                    if (chatType == Canstants.GROUP_CHAT && s.toString().contains("@")) {
                        AtUtil.getInstance().afterTextChanged(etText, targetId);
                    }
                } else {
                    tvSend.setVisibility(View.GONE);
                    ivMore.setVisibility(View.VISIBLE);
                }


            }
        });
        chatAdater.setLongItemClickListener(new AChatPresenter.OnLongItemClickListener() {
            @Override
            public void onLongClick(View v, ChatTableUnit item) {
                AtUtil.getInstance().insertAt(etText, item.getTargetName(), item.getTargetId());
            }
        });
        etText.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                String content = etText.getText().toString();
                if (keyCode == KeyEvent.KEYCODE_DEL) {
                    if (TextUtils.isEmpty(content)) {
                        tvSend.setVisibility(View.GONE);
                        ivMore.setVisibility(View.VISIBLE);
                    }
                }
                return false;
            }
        });
        String draft = (String) SharedUtils.get(this, targetId, "");
        if (!TextUtils.isEmpty(draft)) {
            etText.setText(draft);
        }
        tvUnread.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvUnread.setVisibility(View.GONE);
                if (offset == 1 && !initUnread) {
                    initUnread = true;
//                    MoveToPosition(mLinearLayoutManager, recycleView, 0);
                    int toPosition = chatAdater.getItemCount() - unreadTime - 1;
                    toPosition = toPosition < 0 ? 0 : toPosition;
                    recycleView.scrollToPosition(toPosition);
                    unreadTime = 0;
                    UnReadDown();
                } else {
                    MoveToEnd();
                }

            }
        });
        tvAtel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!atelMap.isEmpty()) {
                    tvAtel.setVisibility(View.VISIBLE);
                    int visibleItemCount = mLinearLayoutManager.getChildCount();
                    int pastVisibleItem = mLinearLayoutManager.findFirstVisibleItemPosition();
                    for (int i = 0; i < chatAdater.getList().size(); i++) {
                        ChatTableUnit t = chatAdater.getList().get(i);
                        ChatTableBean table = ChatTableUnit.getTable(t);
                        if (atelMap.containsKey(table.getId())) {
                            atelMap.remove(table.getId());
                            if (atelMap.isEmpty()) {
                                tvAtel.setVisibility(View.GONE);
                            }
                            if (pastVisibleItem >= i || pastVisibleItem + visibleItemCount < i) {
                                MoveToPosition(mLinearLayoutManager, recycleView, i);
                                return;
                            }
//                            if (pastVisibleItem >= i && pastVisibleItem < pastVisibleItem + visibleItemCount) {
//                            } else {
//                                MoveToPosition(mLinearLayoutManager, recycleView, i);
//                                return;
//                            }
                        }
                    }
                } else {
                    tvAtel.setVisibility(View.GONE);
                }
                addAtelUpdate();
            }
        });
        etText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    MoveToEnd();
                }
            }
        });
        etText.setVisibility(View.GONE);
        switchVoiceClick();
        setReadFinish();
//        swipe.setRefreshing(true);
        getChatList(chatType, targetId, targetId, false);
    }

    private void signLast() {
        if (!chatAdater.getList().isEmpty()) {
            ChatTableUnit last = chatAdater.getList().get(chatAdater.getItemCount() - 1);
            lastItemTime = last.getHistoryTime();
            lastChatType = last.getChatType();
        } else {
            lastItemTime = 0L;
            lastChatType = 0;
        }
    }


    public void initFriendNickName() {
        if (Canstants.SINGLE_CHAT == chatType) {
            ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<String>() {
                @Override
                public void onAction(String obj) {
                    initTitleBar();
                }

                @Override
                public String onThreadAction() {
                    FriendTable tableByFriendUserId = FriendTable.getTableByFriendUserId(targetId);
                    if (tableByFriendUserId != null) {
                        targetName = tableByFriendUserId.getFriendNickname();
                        mFriendAlias = tableByFriendUserId.getFriendAlias();
                    }
                    return targetName;
                }
            });
        } else {
            initTitleBar();
        }
    }

    private void setSelectAllVisibility(int visibility) {
        cbAll.setVisibility(visibility);
        tvDeleteAll.setVisibility(visibility);

        if (visibility == View.VISIBLE) {
            cbAll.setChecked(false);
            llSelectItem.setVisibility(View.VISIBLE);
            switchEmo(true);
            switchGvBox(true);
        }
    }

    private void refreshVisibleItems() {
        int visibleItemCount = mLinearLayoutManager.getChildCount();
        int pastVisibleItem = mLinearLayoutManager.findFirstVisibleItemPosition();
        chatAdater.setPayLoad(pastVisibleItem, visibleItemCount);
    }

    private void initTitleBar() {
        String key = SPKeys.Key.CONFIG_VOICE_PLAY_BY_MAC + UserPreferences.getUserId();
        boolean isMac = SharedPreferenceHelper.create(SPKeys.Name.CONFIG).getBoolean(key, Canstants.DEFAULT_MAC);
        setupTitle(isMac);

        getToolbarRightIv().setVisibility(View.VISIBLE);
        if (chatType == Canstants.GROUP_CHAT) {
            getToolbarRightIv().setImageResource(R.mipmap.icon_black_menu);
        } else if (chatType == Canstants.SINGLE_CHAT) {
            getToolbarRightIv().setImageResource(R.mipmap.tab_btn_setting);
        }

        getToolbarRightIv().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (chatType == Canstants.GROUP_CHAT) {
                    GroupChatSetActivity.jumpTo((Activity) v.getContext(), targetName, targetId, targetType);
                } else {
                    int flag = UserPreferences.isRegistered(targetType) ? Canstants.KEY_REGISTER : Canstants.KEY_VISITOR;
                    FriendInfoActivity.jumpToForResult(GroupChatActivity.this, flag, targetName, targetId, targetType);
                }
            }
        });
    }

    private void setupTitle(boolean isMac) {
        if (Canstants.GROUP_CHAT == chatType) {
            setGroupTitle(targetName, isMac);
        } else {
            setToolbarTitleWithIcon(TextUtils.isEmpty(mFriendAlias) ? targetName : mFriendAlias, 0, isMac);
        }
    }

    private void setGroupTitle(String targetName) {
        String key = SPKeys.Key.CONFIG_VOICE_PLAY_BY_MAC + UserPreferences.getUserId();
        boolean isMac = SharedPreferenceHelper.create(SPKeys.Name.CONFIG).getBoolean(key, Canstants.DEFAULT_MAC);
        try {
            long count = GroupTable.queryRowByGroupId(targetId).getMemberCount();
            setToolbarTitleWithIcon(targetName, count, isMac);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setGroupTitle(String targetName, boolean isMac) {
        try {
            long count = GroupTable.queryRowByGroupId(targetId).getMemberCount();
            setToolbarTitleWithIcon(targetName, count, isMac);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String handleTargetNameLength(String targetName) {
        float fontSize = ChatApp.getInstance().getFontSize();
        int length = 0;
        try {
            length = targetName.getBytes("gbk").length;
            if (FontSize.FONT_NORMAL == fontSize) {
                if (length > 24) {
                    return targetName.substring(0, 12) + "...";
                }
            } else if (FontSize.FONT_OVER_MAX == fontSize) {
                if (length > 18) {
                    return targetName.substring(0, 9) + "...";
                }
            } else if (FontSize.FONT_OVER_MAX2 == fontSize) {
                if (length > 14) {
                    return targetName.substring(0, 7) + "...";
                }
            } else {
                if (length > 26) {
                    return targetName.substring(0, 13) + "...";
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return targetName;
    }

    public void setToolbarTitleWithIcon(String title, long count, boolean isMac) {
        title = handleTargetNameLength(title);
        if (count > 0)
            title = String.format("%s(%s)", title, String.valueOf(count));
        getToolbar().setTitle(title);


        if (isMac) {
            if (ivEar == null) {
                ivEar = new ImageView(this);
                int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3, getResources().getDisplayMetrics());
                ivEar.setPadding(0, padding, 0, 0);
                ivEar.setImageResource(R.mipmap.dialog_icon_earphone_14dp);
            } else {
                getToolbar().removeView(ivEar);
            }
            getToolbar().addView(ivEar);
        } else {
            if (ivEar != null)
                getToolbar().removeView(ivEar);
        }
    }


    public static void jumpTo(Context context, int type, String targetName, String targetId, String targetType) {
        jumpTo(context, type, targetName, targetId, targetType, false);
    }

    public static void jumpTo(Context context, int type, String targetName, String targetId, String targetType, boolean isClear) {
        Intent intent = new Intent(context, GroupChatActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(Canstants.KEY_TYPE, type);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_NAME, targetName);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_ID, targetId);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_TYPE, targetType);
        intent.putExtra(Canstants.KEY_CLEAR_TASK, isClear);
        context.startActivity(intent);
        ChatApp.getInstance().inActivityAnim(context);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        setReadFinish();
        SpeechVoiceUtil.setAudioMute(this, false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        NotificationUtils.setupTargetId(targetId);
        isPause = false;
//        chatAdater.setPause(false);
    }

    @Override
    protected void onPause() {
        super.onPause();
        NotificationUtils.removeTargetId();
        isPause = true;
//        chatAdater.setPause(true);
    }

    /**
     * 设置阅后即焚状态
     */
    private void setReadFinish() {
        if (Canstants.GROUP_CHAT == chatType) {
            isReadFinish = ReadFinishCycTimeUtil.getInstance().isReadFinish(this, Canstants.isGroupReadFinishKey(targetId, ChatApp.getInstance().getUserId()));
            if (isReadFinish) {
                readFinishTime = ReadFinishCycTimeUtil.getInstance().getReadFinish(this, Canstants.getGroupReadFinishKey(targetId, ChatApp.getInstance().getUserId()));
            }
        } else {
            isReadFinish = ReadFinishCycTimeUtil.getInstance().isReadFinish(this, Canstants.isSingleReadFinishKey(targetId, ChatApp.getInstance().getUserId()));
            if (isReadFinish) {
                readFinishTime = ReadFinishCycTimeUtil.getInstance().getReadFinish(this, Canstants.getSingleReadFinishKey(targetId, ChatApp.getInstance().getUserId()));
            }
        }
    }

    @OnClick({R.id.iv_emoj, R.id.tv_send, R.id.iv_take_voice, R.id.iv_more})
    public void onViewClicked(View view) {
        MoveToEnd();
        switch (view.getId()) {

            case R.id.iv_emoj:
                if (etText.getVisibility() == View.GONE) {
                    etText.setVisibility(View.VISIBLE);
                    tvSpeech.setVisibility(View.GONE);
                    etText.setVisibility(View.VISIBLE);
                    etText.setEnabled(true);
                    ivTakeVoice.setImageResource(R.mipmap.dialog_btn_mic);
                    if (!TextUtils.isEmpty(etText.getText().toString())) {
                        tvSend.setVisibility(View.VISIBLE);
                        ivMore.setVisibility(View.GONE);
                    }
                }
                switchGvBox(true);
                switchEmo(false);

                break;
            case R.id.tv_send:
//                Threader.run(() -> {
//                    for (int i = 0; i < 30; i++) {
//                        final int index = i;
//                        runOnUiThread(() -> {
//                            etText.setText("@WC" + (index + 1));
//                            sendTextChat();
//                        });
//                        Threader.sleep(1500);
//                    }
//                });

                if (TextUtils.isEmpty(etText.getText().toString().trim())) {
                    return;
                }
                sendTextChat();
                break;
            case R.id.iv_take_voice:
                switchVoiceClick();
                break;
            case R.id.iv_more:
                switchEmo(true);
                switchGvBox(false);
                break;
//            case R.id.emoji_del:
//                int keyCode = KeyEvent.KEYCODE_DEL;
//                KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode);
//                etText.dispatchKeyEvent(keyEvent);
//                break;
        }
    }

    private void switchVoiceClick() {
        if (etText.getVisibility() == View.VISIBLE) {
            etText.setVisibility(View.GONE);
            etText.setEnabled(false);
            tvSpeech.setVisibility(View.VISIBLE);
            ivTakeVoice.setImageResource(R.mipmap.dialog_btn_keyboard);
            tvSend.setVisibility(View.GONE);
            ivMore.setVisibility(View.VISIBLE);
            switchEmo(true);
        } else {
            tvSpeech.setVisibility(View.GONE);
            etText.setVisibility(View.VISIBLE);
            etText.setEnabled(true);
            ivTakeVoice.setImageResource(R.mipmap.dialog_btn_mic);
            if (!TextUtils.isEmpty(etText.getText().toString())) {
                tvSend.setVisibility(View.VISIBLE);
                ivMore.setVisibility(View.GONE);
            }

        }
    }

    private void switchEmo(boolean isGone) {
        if (emojiconsView.getVisibility() == View.VISIBLE || isGone) {
            gvPanel.setVisibility(View.GONE);
            ivEmoj.setImageResource(R.mipmap.dialog_btn_emoji_n);
            emojiconsView.setVisibility(View.GONE);
        } else {
            if (isGone) {
                return;
            }
            gvPanel.setVisibility(View.VISIBLE);
//            ivEmoj.setImageResource(R.mipmap.dialog_btn_emoji_s);
            ivEmoj.setImageResource(R.mipmap.dialog_btn_keyboard);
            emojiconsView.setVisibility(View.VISIBLE);
            Utility.getUtility().closeKeyboard(this);
        }
    }

    private void switchGvBox(boolean isGone) {
        if (gvBox.getVisibility() == View.VISIBLE || isGone) {
            gvPanel.setVisibility(View.GONE);
            gvBox.setVisibility(View.GONE);
        } else {
            if (isGone) {
                return;
            }
            gvPanel.setVisibility(View.VISIBLE);
            gvBox.setVisibility(View.VISIBLE);
            Utility.getUtility().closeKeyboard(this);
        }
    }

    private void clickTakeVideo() {
        WxVideoPlayUtil.getInstance().startRecord(this, AlbumUtils.getAlbumVideoFile(this, getPackageName(), ChatApp.getInstance().getUserId()).getAbsolutePath(),
                null);
//        AlbumManageUtil
//                .getInstance().recordVideo(this, new AlbumManageUtil.OnAlbumTakeResultListener() {
//            @Override
//            public void onResult(AlbumFile albumFiles) {
//                Long fileId = AlbumManageUtil.insertAlbumFileToTable(albumFiles, AlbumTableBean.TYPE_VIDEO);
//                JLog.d("out put  " + albumFiles.getPath());
////                        if (isOrigin) {
//                sendChat(MsgType.Video, String.valueOf(fileId), albumFiles);
////                        } else {
////                        sendThumbVideo(albumFiles);
////                        }
//            }
//
//            @Override
//            public void onCancel(String result) {
//
//            }
//        });
    }

    private void clickTakePhoto() {
        AlbumManageUtil
                .getInstance().takePicture(this, new AlbumManageUtil.OnAlbumTakeResultListener() {
            @Override
            public void onResult(AlbumFile albumFile) {
                Long fileId = AlbumManageUtil.insertAlbumFileToTable(albumFile, AlbumTableBean.TYPE_IMAGE);
                sendChat(MsgType.Picture, String.valueOf(fileId), albumFile);
            }

            @Override
            public void onCancel(String result) {

            }
        });
    }

    private void clickSelectPhoto() {
        AlbumManageUtil
                .getInstance()
                .selectMultiImage(this, new AlbumManageUtil.OnAlbumBindResultListener() {
                    @Override
                    public void onResult(boolean isOrigin, ArrayList<AlbumFile> albumFiles) {
                        try {
                            Threader.run(() -> {
                                if (albumFiles.size() > 0) {
                                    for (AlbumFile albumFile : albumFiles) {
                                        if (TextUtils.isEmpty(albumFile.getPath())) {
                                            continue;
                                        }
                                        if (AlbumFile.TYPE_VIDEO == albumFile.getMediaType()) {
                                            if (FileSizeUtil.getFileOrFilesSize(albumFile.getPath(), FileSizeUtil.SIZETYPE_MB) > 100.0f) {
                                                showToastSHORT("文件大小不能超过100M");
                                                continue;
                                            }
                                            Long fileId = AlbumManageUtil.insertAlbumFileToTable(albumFile, AlbumTableBean.TYPE_VIDEO);
                                            runOnUiThread(() -> sendChat(MsgType.Video, String.valueOf(fileId), albumFile));
                                            Threader.sleep(1000);
                                        } else {
                                            Long fileId = AlbumManageUtil.insertAlbumFileToTable(albumFile, AlbumTableBean.TYPE_IMAGE);
                                            if (fileId > 0) {
                                                runOnUiThread(() -> sendChat(MsgType.Picture, String.valueOf(fileId), albumFile));
                                            }
                                            Threader.sleep(500);
                                        }

                                    }

                                }

                            });

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onCancel(String result) {
                    }
                });
    }

    /**
     * 页面内消息
     *
     * @param chatType
     * @param targetId
     * @param memberUserId
     * @param msgId
     * @param operation
     */
    private void receiveSingleChat(int chatType, String targetId, String memberUserId, String msgId, int operation) {
        ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<ChatTableBean[]>() {
            @Override
            public void onAction(ChatTableBean[] chat) {
                if (chat != null && chat[0] != null) {
                    hasMsg = true;
                    if (EmptyMessageEvent.REMOVE == operation) {
                        if (recycleView.isComputingLayout()) {
                            recycleView.postDelayed(() -> chatAdater.remove(chat[0].getId()), 300);
                        } else {
                            chatAdater.remove(chat[0].getId());
                        }
                    } else {
                        if (chat[1] != null) {
                            chatAdater.add(ChatTableUnit.copy(chat[1]));
                        }

                        chatAdater.add(ChatTableUnit.copy(chat[0]));
                        int lastPos = mLinearLayoutManager.findLastVisibleItemPosition();
                        if (lastPos == chatAdater.getItemCount() - 2 || lastPos == chatAdater.getItemCount() - 3) {
                            MoveToEnd();
                        } else {
                            ++unreadTime;
                            if (chatAdater.getItemCount() >= 10) {
                                tvUnread.setText(String.format("%d条未读消息", unreadTime));
                                tvUnread.setVisibility(View.VISIBLE);
                            }
                        }
                        if (chatType == Canstants.GROUP_CHAT) {
                            if (chat[0].getChatType() == MsgType.Text && !TextUtils.isEmpty(chat[0].getAtelIds()) && chat[0].getAtelIds().contains(UserPreferences.getUserId())) {
                                atelMap.put(chat[0].getId(), chat[0].getTargetName());
                                addAtelUpdate();
                            }
                        }

                    }
                    signLast();
                }
            }

            @Override
            public ChatTableBean[] onThreadAction() {
                ChatTableBean chat;
                if (chatType == Canstants.GROUP_CHAT) {
                    chat = ChatTableBean.getChatItem(targetId, memberUserId, msgId);
                } else {
                    chat = ChatTableBean.getChatItem(null, targetId, msgId);
                }
                if (chat == null) {
                    return null;
                }
                ChatTableBean lastChat = null;
                if (chatAdater.getItemCount() > 0) {
                    ChatTableUnit uc = chatAdater.getList().get(chatAdater.getItemCount() - 1);
                    if (uc.getChatType() == MsgType.History_Time && chatAdater.getItemCount() >= 2) {
                        uc = chatAdater.getList().get(chatAdater.getItemCount() - 2);
                    }
                    if (uc != null) {
                        lastChat = ChatTableUnit.getTable(uc);
                    }
                }
                if (EmptyMessageEvent.REMOVE != operation && lastChat != null && chat.getMsgId().equals(lastChat.getMsgId())) {
                    return null;
                }

                chat.setMsgTime(System.currentTimeMillis());
                chat.setHistoryTime(System.currentTimeMillis());
                chat.setChecked(false);
                if (chat.getChatUnRead() == ChatTableBean.UNREAD && ScreenPlugReceiver.isIsScreenOpen() && !isPause) {
                    chat.setChatUnRead(ChatTableBean.READED);
                }
                ChatTableBean timeChat = appendHistory(System.currentTimeMillis(), chat.getChatType(), chat.isStartReadFinish(), chat.getReadFinishTime());
                if (timeChat != null) {
                    chat.setRelateId(timeChat.getId());
                }

                ChatTableBean.update(chat);
                return new ChatTableBean[]{chat, timeChat};
            }
        });
    }

    private void refreshFinish() {
        progress.setVisibility(View.GONE);
//        recycleView.postDelayed(() -> swipe.setRefreshing(false), 300);
    }

    private synchronized void getChatList(int chatType, String targetId, String id, boolean isRefresh) {

        ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<List<ChatTableBean>>() {
            @Override
            public void onAction(List<ChatTableBean> obj) {
                if (isFinishing()) {
//                    offset = 1;
                    return;
                }
                if (obj == null || obj.isEmpty()) {
//                    offset = 1;
                    isLoadfinish = true;
                    refreshFinish();
                    return;
                }
                chatAdater.addListAll(ChatTableUnit.copys(obj));
                recycleView.postDelayed(() -> {
                    if (offset != 0) {
                        int mToPosition = obj.size() - 1;//+ mLinearLayoutManager.getChildCount()
                        if (chatAdater.getItemCount() > mToPosition) {
                            MoveToPosition(mLinearLayoutManager, recycleView, mToPosition);
                        }
                    } else {
                        if (unreadTime >= 10) {
                            tvUnread.setText(String.format("%d条未读消息", unreadTime));
                            tvUnread.setVisibility(View.VISIBLE);
                            UnReadUp();
                            MoveToEnd();
                        }
                        addAtelUpdate();
                        signLast();
                    }
                    if (!isRefresh) {
                        offset++;
                    }
                    refreshFinish();
//                    refreshVisibleItems();
                }, 300);

            }

            @Override
            public List<ChatTableBean> onThreadAction() {
                if (offset == 0) {
                    long count = ChatTableBean.queryUnreadChatCount(chatType, targetId);
                    unreadTime = (int) count;
                    if (count > limit) {
                        limit = (int) count;
                    }
                }
                int timeSum = 0;
                List<ChatTableBean> list = ChatTableBean.query(chatType, targetId, id, offset, limit);
                if (list.isEmpty()) {
                    return list;
                }
                ChatTableBean.sort(list);
                if (list != null && !list.isEmpty()) {
                    hasMsg = true;
                    Iterator<ChatTableBean> it = list.iterator();
                    while (it.hasNext()) {
                        ChatTableBean chat = it.next();
                        chat.setChecked(false);
                        if (chat.getChatUnRead() == ChatTableBean.UNREAD) {
                            if (chat.isStartReadFinish()) {
                                chat.setMsgTime(System.currentTimeMillis());
                            }
                            ChatTableBean timeChat = appendHistory(chat.getHistoryTime(), chat.getChatType(), chat.isStartReadFinish(), chat.getReadFinishTime());
                            if (timeChat != null) {
                                chat.setRelateId(timeChat.getId());
                                timeSum += 1;
                            }
                            chat.setChatUnRead(ChatTableBean.READED);

                            if (chatType == Canstants.GROUP_CHAT && chat.getChatType() == MsgType.Text && !TextUtils.isEmpty(chat.getAtelIds()) && chat.getAtelIds().contains(UserPreferences.getUserId())) {
                                atelMap.put(chat.getId(), chat.getTargetName());
                            }
                        }
//                        JLog.d(DateTimeUtil.formatDateTime(chat.getHistoryTime()));
                        if (chat.isStartReadFinish()) {// && !TextUtils.isEmpty(chat.getMsgId())
                            if (chat.getReadFinishSpaceTime() <= 0L) {
                                chat.setStartReadFinish(false);
                                chat.setChatType(MsgType.Read_Finish);
                            }
                        }
                        if (chat.getSendType() == ChatTableBean.SEND) {
                            setLoginUser(chat);
                        } else {
                            if (chatType == Canstants.GROUP_CHAT) {
                                GroupMemberTable g = GroupMemberTable.query(chat.getGroupId(), chat.getTargetId());
                                if (g != null) {
                                    chat.setChatAvatarUrl(g.getGroupMemberAvatar());
                                    chat.setChatAvatarPath(g.getGroupMemberAvatarPath());
                                }
                            } else {
                                ChatContentTable u = ChatContentTable.queryRowByTargetId(targetId, chatType);
                                if (u != null) {
                                    chat.setChatAvatarUrl(u.getTargetAvatarUrl());
                                    chat.setChatAvatarPath(u.getTargetAvatarPath());
                                }
                            }

                        }

                        //isClear &&
                        if (chat.getChatType() == MsgType.Read_Finish || chat.getChatType() == MsgType.Del_Chat_Msg) {
                            ChatTableBean.delete(chat);
                            it.remove();
                            hasMsg = true;
                        } else {
                            ChatTableBean.update(chat);
                        }
                        lastItemTime = chat.getHistoryTime();
                        lastChatType = chat.getChatType();
                    }

                    if (!list.isEmpty()) {
                        if (timeSum != 0) {
                            limit += timeSum;
                            List<ChatTableBean> nList = ChatTableBean.query(chatType, targetId, id, offset, limit);
                            ChatTableBean.sort(nList);
                            return nList;
                        }
                    } else {
                        lastItemTime = 0;
                        lastChatType = 0;
                    }

                }
                return list;
            }
        });
    }

    private void addAtelUpdate() {
        if (!atelMap.isEmpty()) {
            tvAtel.setVisibility(View.VISIBLE);
            ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<ChatTableUnit>() {
                @Override
                public void onAction(ChatTableUnit table) {
                    if (table != null) {
                        tvAtel.setText(String.format("%s@了你", table.getTargetName()));
                    }
                }

                @Override
                public ChatTableUnit onThreadAction() {
                    for (int i = 0; i < chatAdater.getList().size(); i++) {
                        ChatTableUnit table = chatAdater.getList().get(i);
                        if (atelMap.containsKey(table.getId())) {
                            return table;
                        }
                    }
                    return null;
                }
            });
        } else {
            tvAtel.setVisibility(View.GONE);
        }
    }

    public void MoveToEnd() {
        if (chatAdater.getItemCount() == 0) {
            return;
        }
        int n = chatAdater.getItemCount() - 1;
        try {
            recycleView.scrollToPosition(n);
//            mLinearLayoutManager.setSpeedFast();
//            int firstItem = mLinearLayoutManager.findFirstVisibleItemPosition();
//            int lastItem = mLinearLayoutManager.findLastVisibleItemPosition();
//            if (n <= firstItem) {
//                recycleView.smoothScrollToPosition(n);
//            } else if (n <= lastItem) {
//                int top = recycleView.getChildAt(n - firstItem).getTop();
//                recycleView.smoothScrollBy(0, top);
//            } else {
//                recycleView.smoothScrollToPosition(n);
//            }
        } catch (Exception e) {
        }
    }

    public void MoveToPosition(LinearLayoutManager manager, RecyclerView mRecyclerView, int n) {

        try {
            int firstItem = manager.findFirstVisibleItemPosition();
            int lastItem = manager.findLastVisibleItemPosition();
            if (n <= firstItem) {
                mRecyclerView.smoothScrollToPosition(n);
            } else if (n <= lastItem) {
                int top = mRecyclerView.getChildAt(n - firstItem).getTop();
                mRecyclerView.smoothScrollBy(0, top);
            } else {
                mRecyclerView.smoothScrollToPosition(n);
            }
        } catch (Exception e) {
        }
    }


    private ChatTableBean setHistoryTime(long msgTime, long historyTime, boolean isReadFinish, long readFinishTime) {
        ChatTableBean c = new ChatTableBean();
        c.setChatName(targetId);
        c.setFromType(chatType);
        c.setChatUnRead(ChatTableBean.READED);
        c.setLoginUserId(ChatApp.getInstance().getUserId());
        if (Canstants.GROUP_CHAT == chatType) {
            c.setGroupId(targetId);
            c.setGroupType(targetType);
        } else {
            c.setTargetId(targetId);
            c.setTargetType(targetType);
        }
        c.setStartReadFinish(isReadFinish);
        c.setSendState(ChatTableBean.SEND_SUCCESS);
        c.setReadFinishTime(readFinishTime);
        c.setChatType(MsgType.History_Time);
        c.setMsgTime(msgTime);
        c.setHistoryTime(historyTime);
        c.setMsgId(GUID.random());
        return c;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (chatType == Canstants.GROUP_CHAT) {
            AtUtil.getInstance().onActivityResult(etText, requestCode, resultCode, data);
        }
        String[] paths = FileManageActivity.onResultPath(requestCode, resultCode, data);
        if (paths != null && paths.length > 0) {
            Threader.run(() -> {
                for (String path : paths) {
                    if (!TextUtils.isEmpty(path)) {
                        if (FileSizeUtil.getFileOrFilesSize(path, FileSizeUtil.SIZETYPE_MB) > 100.0f) {
                            showToastSHORT("文件大小不能超过100M");
                            continue;
                        }
                        int mineType = AlbumTableBean.getFileType(path);
                        AlbumFile albumFile = AlbumManageUtil.getInstance().getAlbumFile(this, path);
                        int chatType;
                        Long fileId;
                        if (AlbumTableBean.TYPE_VIDEO == mineType) {
                            fileId = AlbumManageUtil.insertAlbumFileToTable(albumFile, AlbumTableBean.TYPE_VIDEO);
                            chatType = MsgType.Video;
                        } else if (AlbumTableBean.TYPE_IMAGE == mineType) {
                            chatType = MsgType.Picture;
                            fileId = AlbumManageUtil.insertAlbumFileToTable(albumFile, AlbumTableBean.TYPE_IMAGE);
                        } else if (AlbumTableBean.isRecordFile(path)) {
                            chatType = MsgType.Voice;
                            fileId = null;
                        } else {
                            chatType = MsgType.ANNEX;
                            fileId = AlbumManageUtil.insertAlbumFileToTable(albumFile, AlbumTableBean.TYPE_EXTRA_FILE);
                        }
                        runOnUiThread(() -> {
                            sendChat(chatType, fileId == null ? null : String.valueOf(fileId), albumFile);
                        });
                        Threader.sleep(500);
                    }
                }
            });

            return;
        }
        if (requestCode == Canstants.REQUEST_CODE_BACK) {
            if (resultCode == Canstants.REQUEST_CODE_BACK) {
                hasMsg = false;
                finish();
            }
            return;
        }
        if (Canstants.MODIFT_TARGETNAME_CODE == requestCode) {
//            chatAdater.notifyDataSetChanged();
            if (Canstants.MODIFT_TARGETNAME_CODE == resultCode) {
                String key = SPKeys.Key.CONFIG_VOICE_PLAY_BY_MAC + UserPreferences.getUserId();
                boolean isMac = SharedPreferenceHelper.create(SPKeys.Name.CONFIG).getBoolean(key, Canstants.DEFAULT_MAC);
                if (Canstants.GROUP_CHAT == chatType) {
                    setGroupTitle(data.getStringExtra(Canstants.KEY_REMARK), isMac);
                } else {
                    mFriendAlias = data.getStringExtra(Canstants.KEY_REMARK);
                    setToolbarTitleWithIcon(TextUtils.isEmpty(mFriendAlias) ? targetName : mFriendAlias, 0, isMac);
                }
            }
            return;
        }
//        if (requestCode == REQ_CODE_ANNEX && data != null) {
//            String path = AndroidFileUtil.getPath2uri(this, data.getData());
//            if (!TextUtils.isEmpty(path)) {
//                if (FileSizeUtil.getFileOrFilesSize(path, FileSizeUtil.SIZETYPE_MB) > 100.0f) {
//                    showToastSHORT("文件大小不能超过100M");
//                    return;
//                }
//                AlbumFile albumFile = AlbumManageUtil.getInstance().getAlbumFile(this, path);
//                Long fileId = AlbumManageUtil.insertAlbumFileToTable(albumFile, AlbumTableBean.TYPE_EXTRA_FILE);
//                sendChat(MsgType.ANNEX, String.valueOf(fileId), albumFile);
//                return;
//            }
//        }
        WxVideoPlayUtil.getInstance().onActivityResult(requestCode, resultCode, data, new WxVideoPlayUtil.OnVideoCallback() {
            @Override
            public void onVideoCall(String videoPath) {
                JLog.d("out video path " + videoPath);
                if (!TextUtils.isEmpty(videoPath)) {
                    AlbumFile albumFile = AlbumManageUtil.getInstance().getAlbumFile(mContext, videoPath);
                    Long fileId = AlbumManageUtil.insertAlbumFileToTable(albumFile, AlbumTableBean.TYPE_VIDEO);
                    sendChat(MsgType.Video, String.valueOf(fileId), albumFile);
                }
            }

            @Override
            public void onPhotoCall(String photoPath) {

            }
        });
    }

    @Override
    public void onItemReloadClick(View view, Object obj, int position) {
        ChatTableBean send = (ChatTableBean) obj;
        if ((send.getChatType() == MsgType.Picture || send.getChatType() == MsgType.Video) && !TextUtils.isEmpty(send.getThumbPath())) {
            File f = new File(send.getThumbPath());
            if (!f.exists()) {
                showToastSHORT("本地文件不存在！");
                if (recycleView.isComputingLayout()) {
                    recycleView.postDelayed(() -> chatAdater.remove(position), 300);
                }else{
                    chatAdater.remove(position);
                }

                return;
            }
        }
        new RectButtonHintDialog(this)
                .setTitle("重新发送")
                .setLeftSubmit("取消", null)
                .setRightSubmit("确认", (v) -> sendChat(send, position)).show();
    }

    @Override
    public void onItemLongClick(View view, Object obj, int position) {
        ChatTableUnit cu = (ChatTableUnit) obj;
        longItem = ChatTableUnit.getTable(cu);
        if (longItem == null || longItem.getSendState() == ChatTableBean.SEND_ING) {
            return;
        }
        chatItemPop.setDataAndTransmit(longItem.getSendType(), longItem.getChatType(), chatType);
        chatItemPop.setPosition(position);
        chatItemPop.getPopupWindow().show(view);
        vTran.setVisibility(View.VISIBLE);
        vTran.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                vTran.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onItemCheckChange(View view, Object obj, int position, boolean isCheck) {
        tvDeleteAll.setText(String.format("(%s)", chatAdater.selected().size()));
    }

    private void sendTextChat() {
        sendChat(MsgType.Text, null, null);
    }

    private void resumeTextState() {
        etText.setText("");
//        switchEmo(true);
//        switchGvBox(true);
//        Utility.getUtility().closeKeyboard(this);
    }


    /**
     * 登录用户信息
     *
     * @param msg
     */
    private void setLoginUser(ChatTableBean msg) {
        if (sendUser != null) {
            if (!TextUtils.isEmpty(sendUser.getAvatar())) {
                msg.setChatAvatarUrl(sendUser.getAvatar());
                msg.setChatAvatarPath(sendUser.getAvatarPath());
            }
            msg.setTargetName(sendUser.getNickname());
            if (TextUtils.isEmpty(sendUser.getUserId())) {
                msg.setTargetId(sendUser.getTemporaryId());
            } else {
                msg.setTargetId(sendUser.getUserId());
            }
            msg.setTargetType(sendUser.getUserType());
        }
    }

    /**
     * @param msgType
     * @param albumId
     * @param albumFile
     */
    public void sendChat(int msgType, String albumId, AlbumFile albumFile) {
        tvSend.setEnabled(false);
        ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<ChatTableBean[]>() {
            @Override
            public void onAction(ChatTableBean[] msg) {
                if (msg != null) {
                    if (msg[1] != null) {
                        chatAdater.add(ChatTableUnit.copy(msg[1]));
                    }
                    request(msg[0], albumFile, chatAdater.getItemCount() - 1, false);
                }
                tvSend.setEnabled(true);
            }

            @Override
            public ChatTableBean[] onThreadAction() {
                try {
                    ChatTableBean timeChat = appendHistory(System.currentTimeMillis(), chatType, isReadFinish, readFinishTime);
                    ChatTableBean msg = new ChatTableBean();
                    setLoginUser(msg);
                    msg.setChatName(targetId);
                    if (chatType == Canstants.GROUP_CHAT) {
                        msg.setGroupId(targetId);
                        msg.setGroupType(targetType);
                    }
                    msg.setFromType(chatType);
                    msg.setSendType(ChatTableBean.SEND);

                    if (!TextUtils.isEmpty(albumId)) {
                        msg.setAlbumId(albumId);
                    } else {
                        if (albumFile != null) {
                            int mediaType = -1;
                            if (msgType == MsgType.Video) {
                                mediaType = AlbumTableBean.TYPE_VIDEO;
                            } else if (msgType == MsgType.Picture) {
                                mediaType = AlbumTableBean.TYPE_IMAGE;
                            } else if (msgType == MsgType.ANNEX) {
                                mediaType = AlbumTableBean.TYPE_EXTRA_FILE;
                            }
                            if (mediaType != -1) {
                                Long tableId = AlbumManageUtil.insertAlbumFileToTable(albumFile, mediaType);
                                msg.setAlbumId(String.valueOf(tableId));
                            }
                            if (msgType == MsgType.Voice) {//插入语音时长
                                msg.setChatAvatarId(String.valueOf(albumFile.getDuration()));
                            }
                        }
                    }
                    if (albumFile != null && !TextUtils.isEmpty(albumFile.getThumbPath())) {
                        msg.setThumbPath(albumFile.getThumbPath());
                    }
                    msg.setChatType(msgType);
                    if (!TextUtils.isEmpty(etText.getText().toString())) {
                        msg.setTextMsg(etText.getText().toString());
                    }

                    msg.setMsgTime(System.currentTimeMillis());
                    msg.setHistoryTime(System.currentTimeMillis());
                    msg.setSendState(ChatTableBean.SEND_ING);
                    msg.setChatUnRead(ChatTableBean.READED);
                    msg.setStartReadFinish(isReadFinish);
                    msg.setReadFinishTime(readFinishTime);
                    if (timeChat != null) {
                        msg.setRelateId(timeChat.getId());
                    }
                    ChatTableBean.insertWithNewMsgID(msg);
                    JLog.d("ST " + msg.getId() + "-" + DateTimeUtil.getCurrentDateHHMMSS());
                    return new ChatTableBean[]{msg, timeChat};
                } catch (Exception e) {
                    return null;
                }
            }
        });
    }

    /**
     * @param fileChat
     */
    public void sendChat(ChatTableBean fileChat, int position) {
        if (fileChat.getChatType() != MsgType.Text && fileChat.getChatType() != MsgType.Voice && TextUtils.isEmpty(fileChat.getAlbumId())) {
            showToastSHORT("本地文件插入失败，无法发送！");
            return;
        }
        ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<ChatTableBean>() {
            @Override
            public void onAction(ChatTableBean msg) {
                request(msg, TextUtils.isEmpty(msg.getThumbPath()) ? null : AlbumManageUtil.getInstance().getAlbumFile(mContext, msg.getThumbPath()), position, true);
            }

            @Override
            public ChatTableBean onThreadAction() {
                fileChat.setSendState(ChatTableBean.SEND_ING);
                fileChat.setStartReadFinish(isReadFinish);
                fileChat.setMsgTime(System.currentTimeMillis());
                fileChat.setHistoryTime(System.currentTimeMillis());
                fileChat.setReadFinishTime(readFinishTime);
                ChatTableBean.updateInx(fileChat);
                return fileChat;
            }
        });
    }

    private ChatTableBean appendHistory(long msgTime, int chatType, boolean isReadFinish, long readFinishTime) {
        if (lastChatType != 0 && (lastChatType >= MsgType.Read_Finish || chatType >= MsgType.Read_Finish)) {
            return null;
        }
        if (lastItemTime != 0L) {
            return appendHistory(msgTime, lastItemTime, isReadFinish, readFinishTime);
        } else {
            return appendHistory(msgTime, 0L, isReadFinish, readFinishTime);
        }
    }

    private ChatTableBean appendHistory(long current, long preview, boolean isReadFinish, long readFinishTime) {
        long longExpend = current - preview;
        if (preview == 0L || longExpend >= historyTimeUnit) {
            ChatTableBean chatTableBean = setHistoryTime(current - 500, current - 500, isReadFinish, readFinishTime);
            ChatTableBean.insertOnly(chatTableBean);
            return chatTableBean;
        }
        return null;
    }

    /**
     * 网络请求
     *
     * @param msg
     */
    private synchronized void request(ChatTableBean msg, AlbumFile albumFile, int position, boolean reQuest) {
        hasMsg = true;
        if (!reQuest && position == chatAdater.getItemCount() - 1) {
            chatAdater.add(ChatTableUnit.copy(msg));
            MoveToEnd();
            signLast();
        }
//        onBottom(position);
        if (msg.getChatType() == MsgType.Video && albumFile != null && !TextUtils.isEmpty(msg.getAlbumId())) {//裁剪进度加请求进度
            ObserverThread.create().onBackGroudThread(() -> {
                if (!TextUtils.isEmpty(albumFile.getPath())) {
                    if (albumFile.getPath().contains("thumb") || FileSizeUtil.getFileOrFilesSize(albumFile.getPath(), FileSizeUtil.SIZETYPE_MB) <= 4.0d) {//代表压缩后
                        runOnUiThread(() -> {
                            if (sendRequest(msg, albumFile)) return;
                            AtUtil.getInstance().clear();
                        });
                    } else {
                        AlbumManageUtil.getInstance().sendThumbVideo((Activity) mContext, albumFile, new AlbumManageUtil.OnAlbumTakeResultListener() {
                            @Override
                            public void onResult(AlbumFile albumFile) {
                                Long fileId = AlbumManageUtil.insertAlbumFileToTable(albumFile, AlbumTableBean.TYPE_VIDEO);
                                if (fileId != null && fileId > 0L) {
                                    //删除压缩前的表数据
                                    AlbumTableBean.delete(Long.valueOf(msg.getAlbumId()));
                                    msg.setAlbumId(String.valueOf(fileId));
                                    ChatTableBean.update(msg);
                                    if (sendRequest(msg, albumFile)) return;
                                    AtUtil.getInstance().clear();
                                }

                            }

                            @Override
                            public void onCancel(String result) {
                                showToastSHORT("视频压缩异常！");
                            }
                        });
                    }
                } else {
                    JLog.e("video path null");
                }

            });

        } else {
            if (sendRequest(msg, albumFile)) return;
            AtUtil.getInstance().clear();
        }

    }

    private boolean sendRequest(ChatTableBean msg, AlbumFile albumFile) {
        if (msg.getChatType() == MsgType.Text) {
            resumeTextState();
            if (Canstants.GROUP_CHAT == chatType) {
                obtainView().doSendChatToGroup(createGroupMemberChatParams(), msg, null, getAt());
            } else {
                obtainView().doSendChatToFriend(createFriendChatParams(), msg, null);
            }
        } else if (msg.getChatType() == MsgType.Voice) {
            if (Canstants.GROUP_CHAT == chatType) {
                obtainView().doSendChatToGroup(createGroupMemberChatParams(), msg, albumFile, getAt());
            } else {
                obtainView().doSendChatToFriend(createFriendChatParams(), msg, albumFile);
            }
        } else {
            if (TextUtils.isEmpty(msg.getAlbumId())) {
                showToastSHORT("文件插入本地失败");
                return true;
            }
            if (albumFile == null) {
                albumFile = AlbumManageUtil.getInstance().getAlbumFileByTableRowId(Long.valueOf(msg.getAlbumId()));
            }
            if (Canstants.GROUP_CHAT == chatType) {
                obtainView().doSendFileChatToGroup(createGroupMemberChatParams(), msg, albumFile, true, getAt());
            } else {
                obtainView().doSendFileChatToFriend(createFriendChatParams(), msg, albumFile, true);
            }
        }
        return false;
    }

    private String getAt() {
        ArrayMap<String, String> userMap = AtUtil.getInstance().getUserMap();
        if (!CollectionUtils.isEmpty(userMap)) {
            StringBuilder builder = new StringBuilder();
            for (Map.Entry<String, String> entry : userMap.entrySet()) {
                builder.append(",");
                builder.append(entry.getValue());
            }
            if (builder.length() > 0)
                builder.deleteCharAt(0);
            return builder.toString();
        }
        return null;
    }

    public void deleteChats(List<ChatTableBean> selected) {
        String friendUserId = targetId;
        String friendUserType = targetType;
        StringBuilder msgIds = new StringBuilder();
        StringBuilder msgFromIds = new StringBuilder();
        StringBuilder timestamps = new StringBuilder();
        StringBuilder chatTypes = new StringBuilder();
        StringBuilder serverPaths = new StringBuilder();
        String msgId;
        String msgFromId;
        String timestamp;
        String chatType;
        String serverPath;
        for (ChatTableBean bean : selected) {
            if (bean == null || ChatTableBean.SEND_FAIL == bean.getSendState() || bean.getId() == null) {
                continue;
            }
            msgId = bean.getMsgId();
            if (TextUtils.isEmpty(msgId))
                msgId = ChatUtils.createMessageId(bean.getId(), UserPreferences.getUserId(), bean.getTargetId(), bean.getMsgTime());
            msgFromId = bean.getTargetId();
            timestamp = String.valueOf(bean.getMsgTime());
            int ctype = MsgType.translateChatType(bean.getChatType());
            chatType = String.valueOf(ctype);

            if (ctype == IMSContacts.MsgContentType.PICTURE || ctype == IMSContacts.MsgContentType.VIDEO || ctype == IMSContacts.MsgContentType.FILE)
                serverPath = bean.getFileUrl();
            else
                serverPath = "-";
            msgIds.append(",").append(msgId);
            msgFromIds.append(",").append(msgFromId);
            timestamps.append(",").append(timestamp);
            chatTypes.append(",").append(chatType);
            serverPaths.append(",").append(serverPath);

        }
        if (msgIds.length() > 0) msgIds.deleteCharAt(0);
        if (msgFromIds.length() > 0) msgFromIds.deleteCharAt(0);
        if (timestamps.length() > 0) timestamps.deleteCharAt(0);
        if (chatTypes.length() > 0) chatTypes.deleteCharAt(0);
        if (serverPaths.length() > 0) serverPaths.deleteCharAt(0);

        if (Canstants.GROUP_CHAT == this.chatType)
            obtainView().doDeleteGroupChat(msgIds.toString(), friendUserId, msgFromIds.toString(), timestamps.toString(), chatTypes.toString(), serverPaths.toString());
        else
            obtainView().doDeleteFriendChat(msgIds.toString(), friendUserId, friendUserType, msgFromIds.toString(), timestamps.toString(), chatTypes.toString(), serverPaths.toString());
    }

    @Override
    protected void onNettyConnectFailure() {
        dismissNet(isShowDefNetDialog());
        if (!NetworkUtil.isConnected(this)) {
            IMSClientHelper.getInstance().onNetworkNotAvailableClear();
        } else {
            JToast.showShort(this, "连接失败");
        }
    }

    private FriendDto createFriendChatParams() {
        FriendDto friendDto = new FriendDto(UserPreferences.isRegistered() ? IMSContacts.UserType.REGISTERED_USER : IMSContacts.UserType.TOURISTS_USER);
        friendDto.setFriendUserId(this.targetId);
        friendDto.setFriendNickname(this.targetName);
        friendDto.setUserType(this.targetType);
        friendDto.setSnapchatStatus(isReadFinish);
        friendDto.setSnapchatTimeLength(readFinishTime);
        return friendDto;
    }

    private GroupMemberDto createGroupMemberChatParams() {
        GroupMemberDto groupMemberDto = new GroupMemberDto(UserPreferences.getUserType());
        groupMemberDto.setGroupMemberId(UserPreferences.getUserId());//1230新加的
        groupMemberDto.setGroupMemberUserId(UserPreferences.getUserId());
        groupMemberDto.setGroupNemberName(UserPreferences.getNickname());
        groupMemberDto.setGroupMemberAvatar(UserPreferences.getAvatar());
        GroupDto groupDto = new GroupDto(UserPreferences.getUserType());
        groupDto.setGroupId(targetId);
        groupDto.setGroupName(this.targetName);
        groupDto.setGroupType(targetType);
        groupDto.setSnapchatStatus(isReadFinish);
        groupDto.setSnapchatTimeLength(readFinishTime);
        groupMemberDto.setGroup(groupDto);
        return groupMemberDto;
    }


    @Override
    protected int setupEventBusRegSite() {
        return EVENT_REG_ON_CREATE;
    }

    @Override
    protected GroupChatView bindNettyMessageView() {
        return new GroupChatView((code, msg, msgId) -> {
            if (chatAdater != null) {
                JLog.e(msgId);
                chatAdater.changeChatSendStateByMsgId(msgId, isReadFinish, code == IMSContacts.ResponseCode.SUCCESS);
            }
            if (code == IMSContacts.ResponseCode.REFUSE) {
                JToast.showShort(GroupChatActivity.this, "对方拒绝接收离线消息");
                return;
            } else if (code == IMSContacts.ResponseCode.NO_NETWORK) {
                JToast.showShort(GroupChatActivity.this, "请检查网络设置");
                return;
            } else if (code == IMSContacts.ResponseCode.TIMEOUT) {
                JToast.showShort(GroupChatActivity.this, "消息发送超时");
                return;
            }
            if (code != IMSContacts.ResponseCode.SUCCESS && !TextUtils.isEmpty(msg))
                JToast.showShort(GroupChatActivity.this, msg);
        });
    }

    @Override
    public void onBottom(int position) {
        recycleView.postDelayed(() -> chatAdater.setPayLoadEnd(position), 300);
    }

    @Override
    protected void onDestroy() {
        setAllowContinueClick(false);
        AlbumManageUtil.getInstance().destroySmallVideo();
        AlbumManageUtil.getInstance().stopVoice();
        SpeechVoiceUtil.setAudioMute(this, false);
        chatAdater.selectInVisible();
        ObserverThread.create().onBackGroudThread(new Runnable() {
            @Override
            public void run() {
                ChatContentTable.updateSumById(getTargetId(), getChatType());
                String text = etText.getText().toString();
//                 || hasMsg
                boolean hasDraft = !TextUtils.isEmpty(text);
                if (hasDraft) {
                    SharedUtils.put(mContext, targetId, text);
                } else {
                    SharedUtils.remove(mContext, targetId);
                }
                ReadFinishTask.delFinishState(chatAdater.getTableList(), isReadFinish);
                AtUtil.getInstance().clear();
                ChatTableUnit lastChat = null;
                MessageEvent event = MessageEvent.cerateUiRefresh(EventConstants.Action.CHAT_REFRESH);
                if (chatAdater.getItemCount() > 0) {
                    lastChat = chatAdater.getList().get(chatAdater.getItemCount() - 1);
                    if (lastChat.getChatType() == MsgType.History_Time && chatAdater.getItemCount() >= 2) {
                        lastChat = chatAdater.getList().get(chatAdater.getItemCount() - 2);
                    }
                }

                if (lastChat != null) {
                    int c = lastChat.getChatType();
                    UserChatTable u = new UserChatTable(targetId, targetName, chatType, lastChat.isStartReadFinish(), c, lastChat.getTextMsg(), lastChat.getHistoryTime());
                    u.setTaskDestory(!hasMsg);
                    u.setReceiveType(UserChatTable.RECEIVE_FROM_ACTIVITY);
                    u.setTargetAlias(mFriendAlias);
                    event.setData(new Gson().toJson(u));
                } else {
                    UserChatTable u = new UserChatTable(targetId, targetName, chatType, isReadFinish, MsgType.Text, null, 0L);
                    ChatContentTable c = ChatContentTable.queryRowByTargetId(targetId, chatType);
                    u.setTaskDestory(c == null ? !hasDraft : !hasMsg);
                    u.setReceiveType(UserChatTable.RECEIVE_FROM_ACTIVITY);
                    u.setTargetAlias(mFriendAlias);
                    event.setData(new Gson().toJson(u));
                }
                EventBus.getDefault().post(event);
            }
        });
        mScreenPlugReceiver.unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUiRefreshNotification(MessageEvent me) {
        if (me == null || TextUtils.isEmpty(me.data()) || me.event() != EventConstants.Event.UI_REFRESH_NOTIFICATION)
            return;
        if (me.action() == EventConstants.Action.GROUP_CHAT_ADD) {
            ChatTableBean msg = new Gson().fromJson(me.data(), ChatTableBean.class);
            if (msg != null && targetId.equals(msg.getGroupId())) {
                chatAdater.add(ChatTableUnit.copy(msg));
                recycleView.scrollToPosition(chatAdater.getItemCount() - 1);
            }
        } else if (me.action() == EventConstants.Action.GROUP_NAME_CHANGED) {
            if (!TextUtils.isEmpty(me.data())) {
                setGroupTitle(me.data());
                targetName = me.data();
            }
        } else if (me.action() == EventConstants.Action.DELETE_GROUP ||
                me.action() == EventConstants.Action.EXIT_GROUP) {
            if (!TextUtils.isEmpty(me.data())) {
                String[] split = me.data().split("_");
                if (split.length > 1) {
                    if (split[1].contains(UserPreferences.getUserId())) {
                        if (me.action() == EventConstants.Action.DELETE_GROUP) {
                            JToast.showShort(this, me.action() == EventConstants.Action.DELETE_GROUP ? "你被移出了群聊" : "你退出了群聊");
                            hasMsg = false;
                            finish();
                        }
                    } else {
                        String key = SPKeys.Key.CONFIG_VOICE_PLAY_BY_MAC + UserPreferences.getUserId();
                        boolean isMac = SharedPreferenceHelper.create(SPKeys.Name.CONFIG).getBoolean(key, Canstants.DEFAULT_MAC);
                        setupTitle(isMac);
                    }
                }
            }
        } else if (me.action() == EventConstants.Action.DISSOLVE_GROUP) {
            if (!TextUtils.isEmpty(me.data()) && me.data().equals(targetId)) {
                JToast.showShort(this, "该群被解散了");
                hasMsg = false;
                finish();
            }
        } else if (me.action() == EventConstants.Action.DELETE_FRIEND) {
            if (!TextUtils.isEmpty(me.data()) && me.data().equals(targetId)) {
                JToast.showShort(this, "对方解除了好友关系");
                hasMsg = false;
                finish();
            }
        } else if (me.action() == EventConstants.Action.GROUP_MEMBER_COUNT_REFRESH) {
            String key = SPKeys.Key.CONFIG_VOICE_PLAY_BY_MAC + UserPreferences.getUserId();
            boolean isMac = SharedPreferenceHelper.create(SPKeys.Name.CONFIG).getBoolean(key, Canstants.DEFAULT_MAC);
            setupTitle(isMac);
        } else if (me.action() == EventConstants.Action.CHAT_MSG_RECEIVE) {
            EmptyMessageEvent message = JsonUtils.fromJson(me.data(), EmptyMessageEvent.class);
            if (!targetId.equals(message.getTargetId()) || message.getChatType() != chatType) {
                return;
            }
            receiveSingleChat(message.getChatType(), message.getTargetId(), message.getMemberUserId(), message.getMsgId(), message.getOperation());
        } else if (me.action() == EventConstants.Action.MESSAGE_CLEAR) {
            if (chatType == Canstants.GROUP_CHAT) {
                ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<GroupMemberTable>() {
                    @Override
                    public void onAction(GroupMemberTable obj) {
                        if (chatAdater != null && obj != null) {
                            chatAdater.removeIn(me.data());
                        }
                    }

                    @Override
                    public GroupMemberTable onThreadAction() {
                        return GroupMemberTable.query(targetId, me.msg());
                    }
                });
            } else {
                if (chatAdater != null && targetId.equals(me.msg())) {
                    chatAdater.removeIn(me.data());
                }
            }
        }
    }

    /**
     * gv box
     *
     * @param parent
     * @param view
     * @param position
     * @param id
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (position) {
            case 0://附件
                //AndroidFileUtil.chooseFile(this, REQ_CODE_ANNEX);
                FileManageActivity.chooseFile(this);
                break;
            case 1://相册
                clickSelectPhoto();
                break;
            case 2://拍照
                clickTakePhoto();
                break;
            case 3://视频录制
                clickTakeVideo();
                break;
        }
    }

    private void UnReadUp() {
        Drawable drawableLeft = getResources().getDrawable(
                R.mipmap.dialog_ic_unread_bubble_arrow_up);

        tvUnread.setCompoundDrawablesWithIntrinsicBounds(drawableLeft,
                null, null, null);
    }

    private void UnReadDown() {
        Drawable drawableLeft = getResources().getDrawable(
                R.mipmap.dialog_ic_unread_bubble_arrow_down);

        tvUnread.setCompoundDrawablesWithIntrinsicBounds(drawableLeft,
                null, null, null);
    }

    private HeadsetPlugReceiver mHeadsetPlugReceiver;

    @Override
    protected void onStart() {
        super.onStart();
        mHeadsetPlugReceiver = new HeadsetPlugReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_HEADSET_PLUG);
        intentFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
        registerReceiver(mHeadsetPlugReceiver, intentFilter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mHeadsetPlugReceiver != null)
            unregisterReceiver(mHeadsetPlugReceiver);
    }
}
